const axios = require('axios')
const cheerio = require('cheerio');
const fs = require("fs");
const request = require('request')
const RunSQL = require('../db/utils') // 执行sql
const { intoData, intoData1 } = require('../db/downIMG/index') // 引入sql
const { formatTime } = require('../../utils/util') // 处理时间



const getWallpaper = (url) => { // 获取微信公众号的壁纸
    const arr = []
    return new Promise((resolve, reject) => {
        axios.get(url).then(res =>{
            const $ = cheerio.load(res.data);
            $('#js_content > section > section > section > section > section > section > section img').each((i, item) => {
                const src = $(item).attr('data-src')
                arr.push(src)
            })
            if(arr.length) {
                getLoad(arr, 'wallpaper')
                resolve(true)
            } else reject(false)
        })
    })
}

const getPortrait = url => { // 获取微信公众号的头像
    const arr = []
    return new Promise((resolve, reject) => {
        axios.get(url).then(res =>{
            const $ = cheerio.load(res.data);
            $('#js_content > section > section > section > section > section > section > section > section > section > section  section img').each((i, item) => {
                const src = $(item).attr('data-src')
                arr.push(src)
            })
            if(arr.length) {
                getLoad(arr, 'portrait')
                resolve(true)
            } else reject(false)
        })
    })
}

const downImg = (url, table) => { // 下载图片
    fs.readdir(`${__dirname}/../../downIMG`, (err, files) => { // 检查是否有这个目录
        if(err) fs.mkdir(`${__dirname}/../../downIMG`, err => {
            if(!err) console.log('创建目录成功')
        })
    })
    const isTime = new Date().getTime()
    let type = ''
    return new Promise((resolve, reject) => { // 下载文件
        request
          .get({ url })
          .on('response', (response) => {
            type = response.headers['content-type'].replace(/^[a-z]+\//g, '')
            response.pipe(fs.createWriteStream(`${__dirname}/../../downIMG/${isTime}.${type}`))
            .on("finish", () => {
                resolve("ok");
              })
          })
          .on("error", (e) => {
            reject(e)
          })
          .on("close", () => { // 下载图片完成， 生成记录
            switch (table) {
                case 'wallpaper':
                    RunSQL(intoData, [isTime, `/downIMG/${isTime}.${type}`, formatTime(new Date()), null]).then(res => {
                        console.log('插入wallpaper数据');
                    })
                    break;
                case 'portrait':
                    RunSQL(intoData1, [isTime, `/downIMG/${isTime}.${type}`, formatTime(new Date()), null]).then(res => {
                        console.log('插入portrait数据');
                    })
                    break;
            }
            
          })
   
      })
}
const getLoad = (arr, table) => {
   downImg(arr[0], table)
    arr = arr.slice(1)
    if(arr.length) {
        setTimeout(() => getLoad(arr, table), 1300)
    } else {
        console.log('没有啦');
        return true
    }
}

module.exports = {
    getWallpaper,
    getPortrait,
    downImg
}